#include "stdafx.h"
#include "SketchPadWidget.h"

SketchPadWidget::SketchPadWidget(QWidget *parent)
	: QGLWidget(parent)
{

}

SketchPadWidget::~SketchPadWidget()
{

}

void SketchPadWidget::initSketchModel()
{
	//TODO change
	this->sketchModel   = new SketchModel(new TreeRenderAgent(), this->width(), this->height());
	this->sketch_active = false;
	this->numPixels		= 0;
	this->max_height    = -9999;
	this->min_height    =  9999;

	emit newSketchStarted(sketchModel);
}

void SketchPadWidget::initializeGL()
{
	makeCurrent();
	qglClearColor(QColor(255, 255, 255));

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0, this->width(), 0, this->height());
	glDisable(GL_DEPTH_TEST);
	glMatrixMode(GL_MODELVIEW);

	glLoadIdentity();
	// Correction because pixels are stored as ints (their top left corner)
	glTranslatef(0.375, 0.375, 0);
}

void SketchPadWidget::mouseMoveEvent(QMouseEvent *event)
{
	int x = event->x();
	int y = this->height() - event->y() - 1;

	if (sketch_active)
	{
		if ( (numPixels == 0) || (pixel[numPixels-1][0] != x) || (pixel[numPixels-1][0] != y) ){
			pixel[numPixels][0] = x;
			pixel[numPixels][1] = y;
			numPixels++;	
		}
	}
	updateGL();
}

void SketchPadWidget::mousePressEvent(QMouseEvent *event)
{
	int x = event->x();
	int y = this->height() - event->y() - 1;

	// TODO LMB vs RMB
	if (!sketch_active)
	{
		sketch_active		= true;
		startTime			= (GLuint) glutGet(GLUT_ELAPSED_TIME);
		numPixels			= 0;
		pixel[numPixels][0] = x;
		pixel[numPixels][1] = y;
		numPixels++;
	}
	updateGL();
}

void SketchPadWidget::mouseReleaseEvent(QMouseEvent *event)
{
	int x = event->x();
	int y = this->height() - event->y() - 1;

	if (sketch_active)
	{
		sketchTime = ( (GLuint) glutGet(GLUT_ELAPSED_TIME) ) - startTime;

		if ( (numPixels == 0) || (pixel[numPixels-1][0] != x) || (pixel[numPixels-1][0] != y) ){
			pixel[numPixels][0] = x;
			pixel[numPixels][1] = y;
			numPixels++;
		}

		CSketch *sketch = new CSketch(numPixels, pixel, startTime, sketchTime, height(), height());
		this->sketchModel->addSketch(sketch);
		emit sketchModelUpdated();

		sketch_active = false;
	}
	updateGL();
}

void SketchPadWidget::paintGL()
{
	makeCurrent();
	glClear(GL_COLOR_BUFFER_BIT);

	if (this->sketch_active)
	{
		// Draw current user input in progress
		glColor3f(0.0, 0.0, 0.0); 
		glPointSize(1.0);
		glBegin(GL_LINE_STRIP);
		for(int i=0; i<numPixels; i++)
			glVertex2iv(pixel[i]);
		glEnd();

		// Call SketchType specific additional 2D rendering
		this->sketchModel->renderSketchInProgress(this->numPixels, this->pixel);
	}

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// Draw all other sketches in the SketchModel
	this->sketchModel->render2D();
}

void SketchPadWidget::resizeGL(int w, int h)
{
	glViewport(0, 0, (GLsizei) w, (GLsizei) h);
}